package com.cangheng.app.util.socketTest;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Server {

	private static long count = 0;
	
	public static List<Socket> socketList = Collections.synchronizedList(new ArrayList<Socket>());
	
	@SuppressWarnings("resource")
	public static void main (String[] args) throws IOException {
		// 创建一个 ServerSocket，用于监听客户端 Socket的连接请求
		ServerSocket ss = new ServerSocket(30000);
		
		String hostName = null;
		String hostAddress = null;
		
		System.out.println("server start...");
		// 采用循环不断接受来自客户端的请求
		while (Boolean.TRUE) {
			// 每当接收到客户端Socket的请求时，服务器也对应产生一个Socket
			Socket s = ss.accept();
			socketList.add(s);
			count ++;
			hostName = s.getInetAddress().getHostAddress();
			hostAddress = s.getInetAddress().getHostName();
			// 打印连接信息
			System.out.println(hostName + " " + hostAddress + " " + count);
			// 每当客户端连接后启动一个 ServerThread线程为该客户端服务
			new Thread(new ServerThread(s)).start();
		}
	}
}
